#!/bin/bash

currentdir=$(cd "$(dirname "$0")"; pwd)
echo "build directory: ${currentdir}."

echo -e "\nbuild pcre..."
if [ ! -d "$currentdir/build/linux" ]; then 
	mkdir -p "$currentdir/build/linux"
else
	rm -rf ${currentdir}/build/linux/*
fi

autoreconf

testarch=$(uname -m)
if [ $testarch = "mips64" ]; then
        sed -i 's/( sleep 1 ) &/sleep 1/1' ./configure
        sed -i 's/am_sleep_pid=$!/#am_sleep_pid=$!/1' ./configure
        echo "mips64 patch ok !"
fi

if [ $testarch = "loongarch64" ]; then
./configure CFLAGS=-fPIC --build=loongarch64-unknown-linux-gnu --enable-utf8 --enable-shared=no --prefix=/usr/local
else
./configure CFLAGS=-fPIC --enable-utf8 --enable-shared=no --prefix=/usr/local
fi
if [ $? -ne 0 ]; then exit 1; fi
make
make install DESTDIR=${currentdir}/build/linux

if [ ! -f "${currentdir}/build/linux/usr/local/lib/libpcre.a" ]; then exit 1; fi
rm -rf ${currentdir}/../../../lib/libpcr*.a
cp -rv "${currentdir}/build/linux/usr/local/lib/libpcre.a" ${currentdir}/../../../lib
cp -rv "${currentdir}/build/linux/usr/local/lib/libpcrecpp.a" ${currentdir}/../../../lib
cp -rv "${currentdir}/build/linux/usr/local/lib/libpcreposix.a" ${currentdir}/../../../lib

make clean
rm -rf ${currentdir}/build/linux/*

echo "====== pcre build success! ======"
exit 0
